﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Linq;
using System.Xml;
using Aulac.Global.Enums;
using Aulac.Global.Data;
using Aulac.Global.Common;
using Aulac.Global.Xml;
using Aulac.Rsc.Ems;
using Aulac.Rsc.Ems.Tags;

using Aulac.Client.Data.Ems.Helper.DataItems;
using Aulac.Verb.Ems;
using Aulac.Client.Data.Helper;
using Aulac.Rsc;
using Aulac.Global.AccessRight;
using Aulac.Client.Global.Interface;
namespace Aulac.Client.Ems.WinForm.Stores
{
    public partial class FormTranferMdnStore
    {
        /*Update code:02/17/2011 by Thangnc */

        private bool mIsCheckInstock = true;
        
        #region Override Methods
        public override void OnFormLoad()
        {
            try
            {
                base.OnFormLoad();
                cboObjRels.AutoLoadData = true;
                cboObjRec.AutoLoadData = true;
                cboRecPsn.LoadDataToControl();
                cboRelsPsn.LoadDataToControl();
                cboRecStore.LoadDataToControl();
                cboRelsStore.LoadDataToControl();
                InitGrdInfo();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        protected override bool OnShowDetailVoucher()
        {
            if (ValueHelper.isEmpty(mVoucherID) || (grdInfo.SelectedGridRowView == -1))
            {
                if (grdLine.grdData.SelectedIndexGridRow != -1)
                    Aulac.UtilityTools.MsgBox.Show("Vui lòng chọn một dòng ở [Danh sách] để hiển thị chi tiết !", Aulac.UtilityTools.MsgBox.Title, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
            base.OnShowDetailVoucher();            
            XmlDataDocument xmlDoc = Aulac.Client.Connect.Ems.DataRequest.CreateXmlDocument(AulacEmsVerb.MngStore.TranStore.GetVchTranStore, AulacEmsVerb.MngStore.TranStore.Noun.TranStore);
            XmlProcess.AddValueParamItem(xmlDoc, tagVch.Inv.VchTranInvPrkID, VchID);
            XmlProcess.AddValueParamItem(xmlDoc, tagVch.Inv.VchTypeID, mVchType);
            XmlDataDocument outDoc = Aulac.Client.Connect.Ems.DataRequest.ProcessRequest(xmlDoc);
            XmlElement eHeader = XmlProcess.GetVchHeaderElm(outDoc);
            XmlNodeList listNode = XmlProcess.GetListVchLineItem(outDoc);
            foreach (Aulac.Client.Global.Interface.IAulacValueDataCtrl ctr in GetListControlsOnForm())
            {
                if (!(ctr is Aulac.Client.Controls.Ems.ComboBo.ComboObjByTypeCtrl))
                    ctr.SetValueToControl(eHeader);
            }

            // Noi giao
            ObjectTypes oType = (ObjectTypes)ValueHelper.ChangeType(XmlProcess.GetValueAtrb(eHeader, tagVch.Inv.ObjTypeRelsID), typeof(ObjectTypes));
            if (oType == ObjectTypes.None)
            {
                oType = ObjectTypes.KHOAPHONG;
                cboObjRels.ComboObjectTyeps.ClearDataContainer();
            }
            cboObjRels.ComboObjectTyeps.ObjTypeID = oType;
            string sObjPrkID = XmlProcess.GetValueAtrb(eHeader, tagVch.Inv.ObjRelsPrkID);
            if (!ValueHelper.isEmpty(sObjPrkID))
                cboObjRels.ObjPrkID = sObjPrkID;
            // Noi nhan
            oType = (ObjectTypes)ValueHelper.ChangeType(XmlProcess.GetValueAtrb(eHeader, tagVch.Inv.ObjTypeRecID), typeof(ObjectTypes));
            if (oType == ObjectTypes.None)
            {
                oType = ObjectTypes.KHOAPHONG;
                cboObjRec.ComboObjectTyeps.ClearDataContainer();
            }
            cboObjRec.ComboObjectTyeps.ObjTypeID = oType;
            sObjPrkID = XmlProcess.GetValueAtrb(eHeader, tagVch.Inv.ObjRecPrkID);
            if (!ValueHelper.isEmpty(sObjPrkID))
                cboObjRec.ObjPrkID = sObjPrkID;

            for (int i = 0; i < listNode.Count; i++)
            {
                XmlElement eLine = listNode.Item(i) as XmlElement;
                string sPrice = XmlProcess.GetValueAtrb(eLine, tagVch.Inv.PrimeCostInExc);
                string sAmtTtl = XmlProcess.GetValueAtrb(eLine, tagVch.Inv.AmtPrimeCostLineInExc);
                XmlProcess.SetAtrb(ref eLine, grdLine.ColumnsGrd.PriceInExc, sPrice);
                XmlProcess.SetAtrb(ref eLine, grdLine.ColumnsGrd.AmtLineInExc, sAmtTtl);
            }            
            grdLine.AddDataToControl(listNode);
            grdLine.SetTotalSummary();
            return true;
        }
        protected override void OnAddNewVoucher()
        {
            /*Update code 02/17/2011 by Thangnc K*/

            mIsCheckInstock = true;
            mVoucherID = "";
            this.grdLine.ShowHideColumn(false, this.grdLine.ColumnsGrd.ItemLine);
            txtNo.Text = GetNewVchNo(ref mVchName);
            if (ValueHelper.isEmpty(mVchName))
                mVchName = Aulac.Client.Data.Ems.Helper.VchHelper.GetVchNameOnServer(mVchType);
            if (!cboRecPsn.IsEmptyDataInList)
                cboRecPsn.ComBoboxData.SelectedIndex = 0;
            if (!cboRelsPsn.IsEmptyDataInList)
                cboRelsPsn.ComBoboxData.SelectedIndex = 0;
            if (!cboRelsStore.IsEmptyDataInList)
                cboRelsStore.ComBoboxData.SelectedIndex = 0;
            if (!cboRecStore.IsEmptyDataInList)
                cboRecStore.ComBoboxData.SelectedIndex = 0;
            cbTagStoreType.TagStoreTypeID = TagStoreTypes.InputBuy;
            cbTagStoreType.Focus();
        }
        protected override bool OnBeginEditVoucher()
        {
            this.grdLine.ShowHideColumn(false, this.grdLine.ColumnsGrd.ItemLine);
            if (cboObjRec.ComboObjectTyeps.IsEmptyDataInList)
                cboObjRec.ComboObjectTyeps.ReLoadDataToControl();
            if (cboObjRels.ComboObjectTyeps.IsEmptyDataInList)
                cboObjRels.ComboObjectTyeps.ReLoadDataToControl();

            return base.OnBeginEditVoucher();
        }
        protected override void OnEditVoucher()
        {
            /*Update code 02/17/2011 by Thangnc */
            mIsCheckInstock = true;
            base.OnEditVoucher();
            cbTagStoreType.Focus();
        }
        protected override bool OnBeginSaveVoucher()
        {
            grdLine.grdData.EndEditingRow(false);
            grdLine.grdData.RemoveAllRowsByColEmpty(tagItems.Item.ItemGrpID, tagItems.Item.ItemID, tagVch.Inv.Quantity);
            if (cboObjRec.IsEmptyValue)
            {
                Aulac.UtilityTools.MsgBox.Show("Bạn phải chọn thông tin nơi nhận!", Aulac.UtilityTools.MsgBox.Title,  MessageBoxButtons.OK, MessageBoxIcon.Error);
                cboObjRec.Focus();
                return false;
            }
            if (cboObjRels.IsEmptyValue)
            {
                Aulac.UtilityTools.MsgBox.Show("Bạn phải chọn thông tin nơi xuất!", Aulac.UtilityTools.MsgBox.Title, MessageBoxButtons.OK, MessageBoxIcon.Error);
                cboObjRels.Focus();
                return false;
            }

            if (cboRelsStore.IsEmptyValue)
            {                
                Aulac.UtilityTools.MsgBox.Show("Bạn phải chọn kho xuất trước khi lưu!", Aulac.UtilityTools.MsgBox.Title, MessageBoxButtons.OK, MessageBoxIcon.Error);
                cboRelsStore.Focus();
                return false;
            }
            if (cboRecStore.IsEmptyValue)
            {                
                Aulac.UtilityTools.MsgBox.Show("Bạn phải chọn kho nhập trước khi lưu!", Aulac.UtilityTools.MsgBox.Title, MessageBoxButtons.OK, MessageBoxIcon.Error);
                cboRecStore.Focus();
                return false;
            }
            
            int iCount = grdLine.ReadOnly == true ? grdLine.grdData.Rows.Count : grdLine.grdData.Rows.Count - 1;
            if (iCount <= 1)
            {
                Aulac.UtilityTools.MsgBox.Show("Bạn chưa nhập thông tin hàng hóa. Bạn phải nhập thông tin hàng hóa trước khi lưu!", Aulac.UtilityTools.MsgBox.Title, MessageBoxButtons.OK, MessageBoxIcon.Error);
                grdLine.Focus();
                return false;
            }
            for (int i = 1; i < iCount; i++)
            {
                int mQuantity = (int)ValueHelper.ChangeType(grdLine.grdData.GetValueDataCell(i, grdLine.ColumnsGrd.Quantity), typeof(int));
                string sItemID = (string)ValueHelper.ChangeType(grdLine.grdData.GetValueDataCell(i, grdLine.ColumnsGrd.ItemID), typeof(string));
                if (mQuantity == 0 || sItemID == null)
                {
                    if (mQuantity == 0)
                        Aulac.UtilityTools.MsgBox.Show(string.Format("Số lượng dòng [ {0} ] không được bằng không !", i), Aulac.UtilityTools.MsgBox.Title, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    else
                        Aulac.UtilityTools.MsgBox.Show(string.Format("Mã y tế ở dòng [ {0} ] đang rỗng !", i), Aulac.UtilityTools.MsgBox.Title, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    grdLine.grdData.SelectedIndexGridRow = i;
                    return false;
                }
            }
            return true;
        }
        protected override bool OnSaveVoucherData(ref XmlDataDocument xmlData)
        {
            return SaveTranferMdnStore(ref xmlData, FormMode);
        }
        protected override void OnEndSaveVoucher(FormModes pEndFormMode, XmlDataDocument xmlData)
        {
            if (this.TaskWorking == TaskWorks.SaveAddData)
            {
                // add moi mot dong vao
                grdInfo.AddDataInParentNodeToControl(XmlProcess.GetVchHeaderElm(GetValueToVchHeader()));
            }
            else if (this.TaskWorking == TaskWorks.SaveEditData)
            {
                // Xoa dong ben list roi add moi vao.
                int iGrdSelect = grdInfo.SelectedGridRowView;
                for (int i = 0; i < grdInfo.ColumnCount; i++)
                {
                    //grdInfo.setvalue
                }
                xmlData = GetValueToVchHeader();
            }
        }
        protected override bool OnDeleteDataVoucher()
        {
            /* Update code: 02/17/2011 by Thangnc */
            try
            {
                XmlDataDocument xmlDoc = CreateXmlDocument(AulacEmsVerb.MngStore.TranStore.DelVchTranStore, AulacEmsVerb.MngStore.TranStore.Noun.TranStore);
                XmlProcess.AddValueParamItem(xmlDoc, tagVch.Inv.VchTranInvPrkID, mVoucherID);
                XmlProcess.AddValueParamItem(xmlDoc, tagVch.Inv.VchTypeID, mVchType);
                ProcessRequest(xmlDoc);
                return true;
            }
            catch (Exception ex)
            {
                Aulac.Global.Exceptions.AulacException x = new Aulac.Global.Exceptions.AulacException(ex);
                if (ErrCodes.ErrorCode.Error0010.Equals(x.ErrorCode))
                {
                    XmlNodeList lst = XmlProcess.GetListVchLineItem(x.XmlEcexption);
                    foreach (XmlElement eLine in lst)
                    {
                        DataRow row = grdLine.AulacDataGrid.GetFirstDataRowByKey(tagVch.Inv.ItemPrkID, XmlProcess.GetValueAtrb(eLine, tagVch.Inv.ItemPrkID));
                        DataTableProcess.SetValueDataRow(row, tagVch.Inv.OverInstock, true);
                    }
                    return false;
                }
                else throw ex;
            }
        }
        protected override void OnSetStateControls(FormModes pFormMode)
        {
            base.OnSetStateControls(pFormMode);
            bool isReadOnly = false;
            if (pFormMode == FormModes.NewMode || pFormMode == FormModes.EditMode)
                isReadOnly = false;
            else
                isReadOnly = true;
            foreach (Aulac.Client.Global.Interface.IAulacStateCtrl ctr in GetListControlsOnForm())
            {
                ctr.FormMode = pFormMode;
                ctr.ReadOnly = isReadOnly;
                ctr.Enabled = !isReadOnly;
            }
            grdLine.FormMode = this.FormMode;
        }
        protected override void OnClearValueControls()
        {
            base.OnClearValueControls();
            foreach (Aulac.Client.Global.Interface.IAulacValueDataCtrl ctr in GetListControlsOnForm())
                ctr.ClearValueControls();
            grdLine.ClearValueControls();
            grdLine.ClearValueTtAmt();
        }
        protected override void OnSetAccessRight(AccessRights accRight)
        {
            base.OnSetAccessRight(accRight);
            if (!accRight.IsAdministrator)
                txtNo.Enabled = false;
            else
                txtNo.Enabled = true;
        }
        protected override void OnRefreshList()
        {
            InitGrdInfo();
            XmlDataDocument xmlDoc = CreateXmlDocument(AulacEmsVerb.MngStore.TranStore.GetListVchTranStore, AulacEmsVerb.MngStore.TranStore.Noun.TranStore);
            XmlProcess.AddValueParamItem(xmlDoc, tagVch.Inv.VchDateFrom, dtVchFromDate.ShortDate);
            XmlProcess.AddValueParamItem(xmlDoc, tagVch.Inv.VchDateTo, dtVchToDate.ShortDate);
            grdInfo.ClearDataContainer();
            DataHelper.GetDataFromServerToControl(grdInfo, xmlDoc);
        }        
        #endregion

        #region Private Methods
        private void Init()
        {
            grdInfo.DataSource = new Aulac.Client.Data.Ems.DataSet.StoreMngs.ViewVchTranStoreDataTable();
            mVchType = VchTypes.VchTranferStore;
            mVchName = Aulac.Client.Data.Ems.Helper.VchHelper.GetVchNameOnServer(mVchType);
            FieldVchPrkID = tagVch.Inv.VchTranInvPrkID;

            grdInfo.LoadColumnShow();

            cbTagStoreType.SetParamTagStoreTypes(
                        TagStoreTypes.RepaireStore,
                        TagStoreTypes.TranferInClinic,
                        TagStoreTypes.TranferInDept,
                        TagStoreTypes.TranferLocal);            
            cboObjRels.SetCollectionsObjTypes(ObjectTypes.None, ObjectTypes.TRAMYTE, ObjectTypes.KHOAPHONG);
            cboObjRec.SetCollectionsObjTypes(ObjectTypes.None, ObjectTypes.TRAMYTE, ObjectTypes.KHOAPHONG);
            cboObjRels.ComboObjectTyeps.WidthCombobox = 40;
            cboObjRec.ComboObjectTyeps.WidthCombobox = 40;

            grdLine.grdData.ShowHideColumns(false, grdLine.ColumnsGrd.ItemGrpID, grdLine.ColumnsGrd.AmtTaxLineInExc, grdLine.ColumnsGrd.AmtTtlLineInExc, grdLine.ColumnsGrd.TaxRate);
            grdLine.ListMdnGrpTypes = new List<ItemGrpTypes>() { ItemGrpTypes.GrpDrug, ItemGrpTypes.GrpEquMdn, ItemGrpTypes.GrpFlood, ItemGrpTypes.GrpMdnMaterials, ItemGrpTypes.GrpTradMdn };
        }
        private void SetFileMember()
        {
            txtNo.FieldMember = tagVch.Inv.VchNo;
            txtNote.FieldMember = tagVch.Inv.Note;
            dtVchDate.FieldMember = tagVch.Inv.VchDate;
            cboObjRec.AddFieldMapping(tagItems.Obj.ObjTypeID, tagVch.Inv.ObjTypeRecID);
            cboObjRec.AddFieldMapping(tagItems.Obj.ObjPrkID, tagVch.Inv.ObjRecPrkID);
            cboObjRels.AddFieldMapping(tagItems.Obj.ObjTypeID, tagVch.Inv.ObjTypeRelsID);
            cboObjRels.AddFieldMapping(tagItems.Obj.ObjPrkID, tagVch.Inv.ObjRelsPrkID);
            cboRecPsn.AddFieldMapping(tagItems.Psn.PsnPrkID, tagVch.Inv.PsnInStockRecPrkID);
            cboRecPsn.AddFieldMapping(tagItems.Psn.PsnName, tagVch.Inv.PsnInStockRecName);
            cboRelsPsn.AddFieldMapping(tagItems.Psn.PsnPrkID, tagVch.Inv.PsnInStockRelPrkID);
            cboRelsPsn.AddFieldMapping(tagItems.Psn.PsnName, tagVch.Inv.PsnInStockRelName);
            cboRelsStore.AddFieldMapping(tagItems.Store.StorePrkID, tagVch.Inv.StoreRelsPrkID);
            cboRelsStore.AddFieldMapping(tagItems.Store.StoreName, tagVch.Inv.StoreRelsName);
            cboRecStore.AddFieldMapping(tagItems.Store.StorePrkID, tagVch.Inv.StoreRecPrkID);
            cboRecStore.AddFieldMapping(tagItems.Store.StoreName, tagVch.Inv.StoreRecName);
        }
        private void ShowDetailData(XmlDataDocument xmlDoc)
        {
            XmlElement eHeader = XmlProcess.GetVchHeaderElm(xmlDoc);

            foreach (Control ctr in GetListControlsOnForm())
                if (ctr is Aulac.Client.Global.Interface.IAulacValueDataCtrl)
                    ((Aulac.Client.Global.Interface.IAulacValueDataCtrl)ctr).SetValueToControl(eHeader);

            cboRelsStore.SetValueToControl(eHeader);
            //txtNote.SetValueToControl(eHeader);
            //txtTaxRate.SetValueToControl(eHeader);

            XmlNodeList nodeList = XmlProcess.GetListVchLineItem(xmlDoc);
            grdLine.AddDataToControl(nodeList);
        }
        private void InitGrdInfo()
        {
            grdInfo.ClearColumsShow();
            grdInfo.AddColumnShow(new Aulac.UtilityTools.ColumnGridViewInfo() { ColCaption = "Ngày CT", ColName = tagGeneral.VchDate, DisplayIndex = 0 });
            grdInfo.AddColumnShow(new Aulac.UtilityTools.ColumnGridViewInfo() { ColCaption = "Số CT", ColName = tagGeneral.VchNo, DisplayIndex = 1 });
            grdInfo.AddColumnShow(new Aulac.UtilityTools.ColumnGridViewInfo() { ColCaption = "Nơi giao", ColName = tagVch.Inv.StoreRelsName, DisplayIndex = 2 });
            grdInfo.AddColumnShow(new Aulac.UtilityTools.ColumnGridViewInfo() { ColCaption = "Nơi nhận", ColName = tagVch.Inv.StoreRecName, DisplayIndex = 3 });
            grdInfo.AddColumnShow(new Aulac.UtilityTools.ColumnGridViewInfo() { ColCaption = "Người giao", ColName = tagVch.Inv.PsnInStockRelName, DisplayIndex = 4 });
            grdInfo.AddColumnShow(new Aulac.UtilityTools.ColumnGridViewInfo() { ColCaption = "Người nhận", ColName = tagVch.Inv.PsnInStockRecName, DisplayIndex = 5 });
            grdInfo.AddColumnShow(new Aulac.UtilityTools.ColumnGridViewInfo() { ColCaption = "Tổng tiền", ColName = tagVch.Inv.AmtSumInExc, DisplayIndex = 6 });
            grdInfo.AddColumnShow(new Aulac.UtilityTools.ColumnGridViewInfo() { ColCaption = "Ghi chú", ColName = tagVch.Inv.Note, DisplayIndex = 7 });
            grdInfo.Columns[tagVch.Inv.Note].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
        }
        private List<IAulacDataControl> GetListControlsOnForm()
        {
            List<Aulac.Client.Global.Interface.IAulacDataControl> mListControl = null;
            GetListAulacDataControls(ref mListControl, grpParner);
            GetListAulacDataControls(ref mListControl, grpVch);
            mListControl.AddRange(new Aulac.Client.Global.Interface.IAulacDataControl[] { cboRelsStore, cboRecStore, txtNote, cbTagStoreType });
            return mListControl;
        }
        private XmlDataDocument GetValueToVchHeader()
        {
            XmlDataDocument xmlDoc = CreateXmlDocument("", "");
            XmlElement eHeader = XmlProcess.AddVchHeaderElm(ref xmlDoc);

            XmlProcess.SetAtrbVchHeader(xmlDoc, tagVch.Inv.VchTranInvPrkID, mVoucherID);
            XmlProcess.SetAtrbVchHeader(xmlDoc, tagVch.Inv.VchNo, txtNo.Text);
            XmlProcess.SetAtrbVchHeader(xmlDoc, tagVch.Inv.VchDate, dtVchDate.Text);
            XmlProcess.SetAtrbVchHeader(xmlDoc, tagVch.Inv.VchName, mVchName);
            XmlProcess.SetAtrbVchHeader(xmlDoc, tagVch.Inv.StoreRecPrkID, cboRecStore.StorePrkID);
            XmlProcess.SetAtrbVchHeader(xmlDoc, tagVch.Inv.StoreRecName, cboRecStore.StoreName);
            XmlProcess.SetAtrbVchHeader(xmlDoc, tagVch.Inv.StoreRelsPrkID, cboRelsStore.StorePrkID);
            XmlProcess.SetAtrbVchHeader(xmlDoc, tagVch.Inv.StoreRelsName, cboRelsStore.StoreName);
            XmlProcess.SetAtrbVchHeader(xmlDoc, tagVch.Inv.PsnInStockRelPrkID, cboRelsPsn.PsnPrkID);
            XmlProcess.SetAtrbVchHeader(xmlDoc, tagVch.Inv.PsnInStockRelName, cboRelsPsn.PsnName);
            XmlProcess.SetAtrbVchHeader(xmlDoc, tagVch.Inv.PsnInStockRecPrkID, cboRecPsn.PsnPrkID);
            XmlProcess.SetAtrbVchHeader(xmlDoc, tagVch.Inv.PsnInStockRecName, cboRecPsn.PsnName);
            XmlProcess.SetAtrbVchHeader(xmlDoc, tagVch.Inv.AmtSumInExc, grdLine.TxtAmtTtlLineInExc.Text);
            return xmlDoc;
        }
        #endregion
    }
}
